home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / share / pyshared / rdflib / util.py < prev    next >
Encoding:
Python Source  |  2009-03-04  |  6.9 KB  |  242 lines

  1. from rdflib.URIRef import URIRef
  2. from rdflib.BNode import BNode
  3. from rdflib.Literal import Literal
  4. from rdflib.Variable import Variable
  5. from rdflib.Graph import Graph, QuotedGraph
  6. from rdflib.Statement import Statement
  7.  
  8. from rdflib.exceptions import SubjectTypeError, PredicateTypeError, ObjectTypeError, ContextTypeError
  9. from rdflib.compat import rsplit
  10. from cPickle import loads
  11.  
  12. def list2set(seq):
  13.     seen = set()
  14.     return [ x for x in seq if x not in seen and not seen.add(x)]
  15.  
  16. def first(seq):
  17.     for result in seq:
  18.         return result
  19.     return None
  20.  
  21. def uniq(sequence, strip=0):
  22.     """removes duplicate strings from the sequence."""
  23.     set = {}
  24.     if strip:
  25.         map(lambda val, default: set.__setitem__(val.strip(), default),
  26.             sequence, [])
  27.     else:
  28.         map(set.__setitem__, sequence, [])
  29.     return set.keys()
  30.  
  31. def more_than(sequence, number):
  32.     "Returns 1 if sequence has more items than number and 0 if not."
  33.     i = 0
  34.     for item in sequence:
  35.         i += 1
  36.         if i > number:
  37.             return 1
  38.     return 0
  39.  
  40. def term(str, default=None):
  41.     """See also from_n3"""
  42.     if not str:
  43.         return default
  44.     elif str.startswith("<") and str.endswith(">"):
  45.         return URIRef(str[1:-1])
  46.     elif str.startswith('"') and str.endswith('"'):
  47.         return Literal(str[1:-1])
  48.     elif str.startswith("_"):
  49.         return BNode(str)
  50.     else:
  51.         msg = "Unknown Term Syntax: '%s'" % str
  52.         raise Exception(msg)
  53.  
  54.  
  55.  
  56. from time import mktime, time, gmtime, localtime, timezone, altzone, daylight
  57.  
  58. def date_time(t=None, local_time_zone=False):
  59.     """http://www.w3.org/TR/NOTE-datetime ex: 1997-07-16T19:20:30Z
  60.  
  61.     >>> date_time(1126482850)
  62.     '2005-09-11T23:54:10Z'
  63.  
  64.     @@ this will change depending on where it is run
  65.     #>>> date_time(1126482850, local_time_zone=True)
  66.     #'2005-09-11T19:54:10-04:00'
  67.  
  68.     >>> date_time(1)
  69.     '1970-01-01T00:00:01Z'
  70.  
  71.     >>> date_time(0)
  72.     '1970-01-01T00:00:00Z'
  73.     """
  74.     if t is None:
  75.         t = time()
  76.  
  77.     if local_time_zone:
  78.         time_tuple = localtime(t)
  79.         if time_tuple[8]:
  80.             tz_mins = altzone // 60
  81.         else:
  82.             tz_mins = timezone // 60
  83.         tzd = "-%02d:%02d" % (tz_mins // 60, tz_mins % 60)
  84.     else:
  85.         time_tuple = gmtime(t)
  86.         tzd = "Z"
  87.  
  88.     year, month, day, hh, mm, ss, wd, y, z = time_tuple
  89.     s = "%0004d-%02d-%02dT%02d:%02d:%02d%s" % ( year, month, day, hh, mm, ss, tzd)
  90.     return s
  91.  
  92. def parse_date_time(val):
  93.     """always returns seconds in UTC
  94.  
  95.     # tests are written like this to make any errors easier to understand
  96.     >>> parse_date_time('2005-09-11T23:54:10Z') - 1126482850.0
  97.     0.0
  98.  
  99.     >>> parse_date_time('2005-09-11T16:54:10-07:00') - 1126482850.0
  100.     0.0
  101.  
  102.     >>> parse_date_time('1970-01-01T00:00:01Z') - 1.0
  103.     0.0
  104.  
  105.     >>> parse_date_time('1970-01-01T00:00:00Z') - 0.0
  106.     0.0
  107.     >>> parse_date_time("2005-09-05T10:42:00") - 1125916920.0
  108.     0.0
  109.     """
  110.  
  111.     if "T" not in val:
  112.         val += "T00:00:00Z"
  113.  
  114.     ymd, time = val.split("T")
  115.     hms, tz_str = time[0:8], time[8:]
  116.  
  117.     if not tz_str or tz_str=="Z":
  118.         time = time[:-1]
  119.         tz_offset = 0
  120.     else:
  121.         signed_hrs = int(tz_str[:3])
  122.         mins = int(tz_str[4:6])
  123.         secs = (cmp(signed_hrs, 0) * mins + signed_hrs * 60) * 60
  124.         tz_offset = -secs
  125.  
  126.     year, month, day = ymd.split("-")
  127.     hour, minute, second = hms.split(":")
  128.  
  129.     t = mktime((int(year), int(month), int(day), int(hour),
  130.                 int(minute), int(second), 0, 0, 0))
  131.     t = t - timezone + tz_offset
  132.     return t
  133.  
  134. def from_n3(s, default=None, backend=None):
  135.     """ Creates the Identifier corresponding to the given n3 string. WARNING: untested, may contain bugs. TODO: add test cases."""
  136.     if not s:
  137.         return default
  138.     if s.startswith('<'):
  139.         return URIRef(s[1:-1])
  140.     elif s.startswith('"'):
  141.         # TODO: would a regex be faster?
  142.         value, rest = rsplit(s, '"', 1)
  143.         value = value[1:] # strip leading quote
  144.         if rest.startswith("@"):
  145.             if "^^" in rest:
  146.                 language, rest = rsplit(rest, '^^', 1)
  147.                 language = language[1:] # strip leading at sign
  148.             else:
  149.                 language = rest[1:] # strip leading at sign
  150.                 rest = ''
  151.         else:
  152.             language = None
  153.         if rest.startswith("^^"):
  154.             datatype = rest[3:-1]
  155.         else:
  156.             datatype = None
  157.         value = value.replace('\\"', '"').replace('\\\\', '\\').decode("unicode-escape")
  158.         return Literal(value, language, datatype)
  159.     elif s.startswith('{'):
  160.         identifier = from_n3(s[1:-1])
  161.         return QuotedGraph(backend, identifier)
  162.     elif s.startswith('['):
  163.         identifier = from_n3(s[1:-1])
  164.         return Graph(backend, identifier)
  165.     else:
  166.         if s.startswith("_:"):
  167.             return BNode(s[2:])
  168.         else:
  169.             return BNode(s)
  170.  
  171. def check_context(c):
  172.     if not (isinstance(c, URIRef) or \
  173.             isinstance(c, BNode)):
  174.         raise ContextTypeError("%s:%s" % (c, type(c)))
  175.  
  176. def check_subject(s):
  177.     """ Test that s is a valid subject identifier."""
  178.     if not (isinstance(s, URIRef) or isinstance(s, BNode)):
  179.         raise SubjectTypeError(s)
  180.  
  181. def check_predicate(p):
  182.     """ Test that p is a valid predicate identifier."""
  183.     if not isinstance(p, URIRef):
  184.         raise PredicateTypeError(p)
  185.  
  186. def check_object(o):
  187.     """ Test that o is a valid object identifier."""
  188.     if not (isinstance(o, URIRef) or \
  189.             isinstance(o, Literal) or \
  190.             isinstance(o, BNode)):
  191.         raise ObjectTypeError(o)
  192.  
  193. def check_statement((s, p, o)):
  194.     if not (isinstance(s, URIRef) or isinstance(s, BNode)):
  195.         raise SubjectTypeError(s)
  196.  
  197.     if not isinstance(p, URIRef):
  198.         raise PredicateTypeError(p)
  199.  
  200.     if not (isinstance(o, URIRef) or \
  201.             isinstance(o, Literal) or \
  202.             isinstance(o, BNode)):
  203.         raise ObjectTypeError(o)
  204.  
  205. def check_pattern((s, p, o)):
  206.     if s and not (isinstance(s, URIRef) or isinstance(s, BNode)):
  207.         raise SubjectTypeError(s)
  208.  
  209.     if p and not isinstance(p, URIRef):
  210.         raise PredicateTypeError(p)
  211.  
  212.     if o and not (isinstance(o, URIRef) or \
  213.                   isinstance(o, Literal) or \
  214.                   isinstance(o, BNode)):
  215.         raise ObjectTypeError(o)
  216.  
  217. def graph_to_dot(graph, dot):
  218.     """ Turns graph into dot (graphviz graph drawing format) using pydot. """
  219.     import pydot
  220.     nodes = {}
  221.     for s, o in graph.subject_objects():
  222.         for i in s,o:
  223.             if i not in nodes.keys():
  224.                 nodes[i] = i
  225.     for s, p, o in graph.triples((None,None,None)):
  226.         dot.add_edge(pydot.Edge(nodes[s], nodes[o], label=p))
  227.  
  228.  
  229. if __name__ == "__main__":
  230.     # try to make the tests work outside of the time zone they were written in
  231.     #import os, time
  232.     #os.environ['TZ'] = 'US/Pacific'
  233.     #try:
  234.     #    time.tzset()
  235.     #except AttributeError, e:
  236.     #    print e
  237.         #pass
  238.         # tzset missing! see
  239.         # http://mail.python.org/pipermail/python-dev/2003-April/034480.html
  240.     import doctest
  241.     doctest.testmod()
  242.